﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Net8.Project.Common;
using Net8.Project.Common.Extensions;
using Serilog;

namespace Net8.Project.Extension.MiniProfiler
{
    /// <summary>
    /// MiniProfiler性能分析 启动服务
    /// </summary>
    public static class MiniProfilerSetup
    {
        public static void AddMiniProfilerSetup(this IServiceCollection services)
        {
            ArgumentNullException.ThrowIfNull(services);
            if (!AppSettings.App("Middleware", "MiniProfiler", "Enabled").ObjToBool()) return;

            // MiniProfiler配置
            services.AddMiniProfiler(options =>
            {
                options.RouteBasePath = "/profiler"; // 设置MiniProfiler的路由前缀
                options.PopupShowTimeWithChildren = true; // 显示子查询的时间
                options.PopupMaxTracesToShow = 10; // 弹出窗口中显示的最大跟踪数
                options.ResultsAuthorize = request => true; // 允许所有请求访问结果
            });

            // 3.x使用MiniProfiler，必须要注册MemoryCache服务
            // services.AddMiniProfiler(options =>
            // {
            //     options.RouteBasePath = "/profiler";
            //     //(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(10);
            //     options.PopupRenderPosition = StackExchange.Profiling.RenderPosition.Left;
            //     options.PopupShowTimeWithChildren = true;

            //     // 可以增加权限
            //     //options.ResultsAuthorize = request => request.HttpContext.User.IsInRole("Admin");
            //     //options.UserIdProvider = request => request.HttpContext.User.Identity.Name;
            // }
            //);
        }

        public static void UseMiniProfilerSetup(this IApplicationBuilder app)
        {
            ArgumentNullException.ThrowIfNull(app);

            try
            {
                if (AppSettings.App("Middleware", "MiniProfiler", "Enabled").ObjToBool())
                {
                    // 性能分析
                    app.UseMiniProfiler();
                }
            }
            catch (Exception e)
            {
                Log.Error($"An error was reported when starting the MiniProfilerMildd.\n{e.Message}");
                throw;
            }
        }
    }
}
